
import "./index.less"
import { Space, Table, Tag, Input, Button, message, TablePaginationConfig, Modal, Form, Select, InputNumber, Popconfirm } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';
import { getOrderList, getAllProduct, getAllUser, addOrder, handlerOrder, deleteOrder } from "@/api/order"
import { useEffect, useRef, useState } from "react";
import systme from "@/api/constant"
import type { SelectProps } from 'antd';
interface orderType {
    "count": number,
    "id": string,
    "orderNo": string,
    "orderTime": string,
    "pageIndex": number,
    "pageSize": number,
    "productId": string,
    "productName": string,
    "status": number,
    "total": number,
    "userId": string,
    "userName": string
}
interface productType {
    "id": string,
    "img": string | any,
    "name": string,
    "pageIndex": number,
    "pageSize": number,
    "price": number,
    "saleroom": number,
    "sales": number,
    "stock": number,
    "typeId": string,
    "typeName": string
}

interface userType {
    "account": string,
    "address": string,
    "createDate": string,
    "id": string,
    "loginDate": string,
    "pageIndex": number,
    "pageSize": number,
    "password": string,
    "userName": string
}


let searchValue = {
    orderNo: '',
    pageIndex: 1,
    pageSize: 10
}

const formateStatus = (status: number) => {
    let statusCN = ['待发货', '运输中', '已签收']

    return statusCN[status]
}

export default function order() {
   const initSearchData = () =>{
    searchValue = {
        orderNo: '',
        pageIndex: 1,
        pageSize: 10
    }
   }


    const handlerSearch = (e: any) => {
        searchValue.orderNo = e.target.value
    }
    const search = () => {
        searchValue.pageIndex = 1
        initOrderList()
    }

    const handlerAdd = () => {
        setCount(1)
        setIsModalOpen(true)
    }
    const [loading, setLoading] = useState(true)
    const columns: ColumnsType<orderType> = [
        {
            title: '订单号',
            dataIndex: 'orderNo',
            key: 'orderNo',
        },
        {
            title: '客户名',
            dataIndex: 'userName',
            key: 'userName',

        },

        {
            title: '下单时间',
            key: 'orderTime',
            render: (_, record: orderType) => (
                <Space size="middle">
                    <div>
                        {record.orderTime.slice(0, 10)}
                    </div>
                </Space>
            )
        },
        {
            title: '状态',
            key: 'status',
            render: (_, record: orderType) => (
                <div>
                    {formateStatus(record.status)}
                </div>
            ),
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record: orderType) => (
                <Space size="middle">
                    {record.status == 0 && <a style={{ color: 'green' }} onClick={() => { updateOrder(1, record.id) }}>发货</a>}
                    {record.status == 1 && <a onClick={() => { updateOrder(2, record.id) }} >签收</a>}
                    <Popconfirm
                        title="提示"
                        description="是否删除该用户？"
                        onConfirm={() => { handlerDelete(record.id) }}
                        okButtonProps={{ loading: confirmLoading }}
                        onCancel={cancel}

                    >
                        <a style={{ color: 'red' }} >删除订单</a>
                    </Popconfirm>
                </Space>
            ),
        },
    ];
    const [confirmLoading, setConfirmLoading] = useState(false);
    const cancel = () => {
        message.info('取消了删除操作')
    }
    const handlerDelete = (id: string) => {
        setConfirmLoading(true)
        deleteOrder({ id }).then((res) => {
            if (res.code == 200) {
                message.success("删除成功")
                initOrderList()
            } else {
                message.error(res.msg || systme.ERROR_MESSAGE)
            }
            setConfirmLoading(false)
        }).catch((err) => {
            message.error(systme.ERROR_ACTION)
            setConfirmLoading(false)
        })
    }
    const updateOrder = (e: number, id: string) => {
        handlerOrder({ id, status: e }).then((res) => {
            if (res.code == 200) {
                message.success("处理成功")
                initOrderList()
            } else {
                message.error(res.msg || systme.ERROR_MESSAGE)
            }
        }).catch((err) => {
            message.error(systme.ERROR_ACTION)
        })
    }


    const [data, setData] = useState<orderType[]>([])
    const PageChange = (page: number, pageSize: number) => {
        searchValue.pageIndex = page
        searchValue.pageSize = pageSize
        setLoading(true)
        setConfig({ ...saveValue.current, pageSize, current: page })
        initOrderList()
    }

    const initOrderList = (data = searchValue) => {
        getOrderList(data).then((res) => {
            if (res.code == 200) {
                setData(res.data.list)
                setConfig({ ...saveValue.current, total: res.data.total })
            } else {
                message.error(res.msg || systme.ERROR_MESSAGE)
            }
            setLoading(false)
        }).catch((error) => {
            message.error(error || systme.ERROR_MESSAGE)
            setLoading(false)
        })
    }

    let pageConfig: TablePaginationConfig = {
        position: ['bottomCenter'],
        total: 0,
        showTotal: (total: number) => `共 ${total} 条`,
        pageSizeOptions: [10, 20, 30, 40, 50],
        showSizeChanger: true,
        showQuickJumper: true,
        onChange: PageChange,
        pageSize: 10,
        current: 1

    }
    let [config, setConfig] = useState((pageConfig))
    let saveValue = useRef<TablePaginationConfig>()
    useEffect(() => {
        //储存数据
        saveValue.current = config
    }, [config])

    useEffect(() => {
        initSearchData()
        initOrderList()
    }, [])

    const [title, settitle] = useState<string>('创建订单')
    const [form] = Form.useForm();
    const [isModalOpen, setIsModalOpen] = useState(false);
    const handleOk = () => {
        form.validateFields().then((values) => {
            console.log(values);
            values.total = total
            values.productId = selectData?.id
            values.status = 0
            values.userId = selectUserData?.id
            addOrder(values).then((res) => {
                if (res.code == 200) {
                    setIsModalOpen(false)
                    message.success("操作成功")
                    setTotal(0)
                    form.resetFields()
                    searchValue.pageIndex = 1
                    initOrderList()
                } else {
                    message.error(res.msg || systme.ERROR_MESSAGE)
                }
            }).catch((err) => {
                message.error(systme.ERROR_MESSAGE)
            })
        }).catch(error => { message.error(systme.ERROR_ACTION) })
    };
    const handleCancel = () => {
        setIsModalOpen(false)
    };

    const [searchdata, setSearchData] = useState<SelectProps['options']>([]);
    const [searchUserdata, setSearchUserData] = useState<SelectProps['options']>([]);
    const [value, setValue] = useState<string>();
    const [userValue, setUserValue] = useState<string>();
    const [selectData, setSelectData] = useState<productType>()
    const [selectUserData, setSelectUserData] = useState<userType>()
    const handleSearch = (newValue: string) => {
        if (newValue) {

            getAllProduct({ name: newValue }).then((res) => {
                if (res.code == 200) {
                    setSearchData(res.data)

                } else {
                    message.error(res.msg || systme.ERROR_MESSAGE)
                }
            }).catch((err) => {
                message.error(systme.ERROR_MESSAGE)
            })
        } else {
            setSearchData([]);
        }
    };
    const handleUserSearch = (newValue: string) => {
        if (newValue) {

            getAllUser({ userName: newValue }).then((res) => {
                if (res.code == 200) {
                    setSearchUserData(res.data)

                } else {
                    message.error(res.msg || systme.ERROR_MESSAGE)
                }
            }).catch((err) => {
                message.error(systme.ERROR_MESSAGE)
            })
        } else {
            setSearchUserData([]);
        }
    };
    const handleChange = (newValue: string, option: any) => {
        setSelectData(option)
        setValue(newValue);

    };
    const handleUserChange = (newValue: string, option: any) => {
        setSelectUserData(option)
        setUserValue(newValue);

    };
    const [total, setTotal] = useState<number>()
    const [count, setCount] = useState<number>(1)
    const handelrBuyNumber = (e: number) => {
        setTotal(e * (selectData as any).price || 0)
    }
    return (
        <div className="box_views">
            <div className="header flex">
                <div className="header_search flex">
                    <div className="item">
                        <Input placeholder="请输入订单编号" allowClear onChange={(e: unknown) => { handlerSearch(e) }} />
                    </div>
                    <Button type="primary" icon={<SearchOutlined />} size="middle" onClick={search}>查询</Button>

                </div>
                <div className="addBtn">
                    <Button type="primary" icon={<PlusOutlined />} size="middle" onClick={handlerAdd}>创建订单</Button>
                </div>
            </div>
            <Table columns={columns} dataSource={data} pagination={config} rowKey={item => item.id} loading={loading} />
            <Modal title={title} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} width={800}>
                <div className="flex_j_c">
                    <Form
                        name="basic"
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                        style={{ width: 700 }}
                        form={form}
                    >
                        <Form.Item
                            label="产品名称"
                            name="productName"
                            rules={[{ required: true, message: '请选择产品' }]}
                        >
                            <Select
                                showSearch
                                value={value}
                                placeholder='请输入产品名称'
                                style={{ width: 200 }}
                                defaultActiveFirstOption={false}
                                showArrow={false}
                                filterOption={false}
                                onSearch={handleSearch}
                                onChange={handleChange}
                                notFoundContent={null}
                                options={(searchdata || []).map((d) => ({
                                    value: d.name,
                                    label: d.name,
                                    price: d.price,
                                    stock: d.stock,
                                    id: d.id
                                }))}
                            />
                        </Form.Item>
                        <Form.Item
                            label="产品价格"
                        >
                            <div>
                                {selectData?.price}
                            </div>
                        </Form.Item>
                        <Form.Item
                            label="产品库存"
                        >
                            <div>
                                {selectData?.stock}
                            </div>
                        </Form.Item>
                        <Form.Item
                            label="购买客户"
                            name="userName"

                        >
                            <Select
                                showSearch
                                value={userValue}
                                placeholder='请输入客户名称'
                                style={{ width: 200 }}
                                defaultActiveFirstOption={false}
                                showArrow={false}
                                filterOption={false}
                                onSearch={handleUserSearch}
                                onChange={handleUserChange}
                                notFoundContent={null}
                                options={(searchUserdata || []).map((d) => ({
                                    value: d.userName,
                                    label: d.userName,
                                    userId: d.userId,
                                    userName: d.userName
                                }))}
                            />
                        </Form.Item>
                        <Form.Item
                            label="购买数量"
                            name="count"
                            rules={[{ required: true, message: '请输入购买数量' }]}
                        >
                            <InputNumber placeholder="请输入购买数量" value={count} min={1} max={selectData?.stock} onChange={(e: any) => { handelrBuyNumber(e) }} disabled={selectData?.stock ? false : true} />
                        </Form.Item>
                        <Form.Item
                            label="总金额"
                        >
                            {total}
                        </Form.Item>
                    </Form>
                </div>
            </Modal>
        </div>
    )
}